<template>
  <div>
    <a-descriptions :align="{ label: 'right' }">
      <a-descriptions-item label="车辆费用单号">{{ feeDetail?.businesCode || '-' }}</a-descriptions-item>
      <a-descriptions-item label="车辆费用金额">{{ feeDetail?.otherFeeTotalAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆实付金额">{{ feeDetail?.otherFeeHarvestAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆待付金额">{{ feeDetail?.otherFeePayableAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆实收金额">{{ feeDetail?.otherFeeNetReceiptsAmount }} 元</a-descriptions-item>
      <a-descriptions-item label="车辆待收金额">{{ feeDetail?.otherFeePayableAmountHarvest }} 元</a-descriptions-item>
    </a-descriptions>
  </div>
  <a-alert title="请注意：" style="margin-top: 24px; margin-bottom: 20px"> 【借调费】需按分期顺序确认账单，不支持跳期确认账单 </a-alert>
  <table-index
    class="insure-card-table"
    :table="tableCompulsory"
    :selectedKeys="selectedRowKeys"
    @selection-change="selectionChange"
    @loadData="loadData"
  >
    <template #expand-icon="{ expanded, record }">
      <span v-if="record.feeNameId == 61">
        <icon-plus-circle class="icon-custom" v-if="!expanded" />
        <icon-minus-circle class="icon-custom" v-else />
      </span>
    </template>
    <template #feeCategoryName="{ record }">
      <div v-if="record.installment == 0 || record.feeNameId == 61">{{ record.feeName }}</div>
      <div v-else>{{ record.feeCategoryName }} - {{ record.feeName }}</div>
    </template>
    <template #dueDate="{ record }">
      <div> {{ record.dueDate ? dayjs(record.dueDate).format('YYYY-MM-DD') : '-' }}</div>
    </template>
  </table-index>
  <ConfirmCost ref="confirm_cost" @confirm="handleConfirmToFetch" />
  <modifyCost ref="modifyCostRef" @confirm="refreshData" />
</template>
<script setup>
  import { ref, reactive, computed, watch } from 'vue'
  import { getFeeInfoList, checkBatchConfirm } from '@/api/asset/carTransfer'
  import dayjs from 'dayjs'
  import { Message } from '@arco-design/web-vue'
  import ConfirmCost from '../../compoents/confirm-cost.vue'
  import EditFee from '../../compoents/editFee.vue'
  import EditFeeNoByStages from '../../compoents/noByStages.vue'
  import carPaymentPlanModal from '../../../../car/car-manage/components/car-payment-plan-modal.vue'
  import modifyCost from '../../../../car/car-manage/modify-cost.vue'
  import { useTable } from '@/hooks/table'

  const props = defineProps({
    carId: {
      type: [Number, String],
    },
    type: {
      type: [Number, String],
    },
    code: {
      type: [Number, String],
    },
  })

  const pagination = { pageSize: 1000 }

  const selectedKeys = ref([])

  const feeDetail = ref({})

  const queryParam = reactive({
    feeCategoryList: [6],
    carId: props.carId,
    businesCode: props.code,
  })
  const tableCompulsory = useTable({
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      { title: '费用名称', dataIndex: 'feeCategoryName', width: 180, slotName: 'feeCategoryName', fixed: 'left' },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 120 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 120 },
      {
        title: '应结日期',
        dataIndex: 'dueDate',
        slotName: 'dueDate',
        width: 140,
      },
      { title: '费用金额(元)', dataIndex: 'totalAmount', width: 140 },
      { title: '实结金额(元)', dataIndex: 'payAmount', width: 140 },
      { title: '待结金额(元)', dataIndex: 'outstandingAmount', width: 140 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 120 },
      { title: '生成时间', dataIndex: 'createTime', width: 180 },
      { title: '收支方式', dataIndex: 'payTypeName', width: 120 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 120 },
      { title: '实结时间', dataIndex: 'payTime', width: 180 },
      { title: '确认时间', dataIndex: 'confirmTime', width: 180 },
      { title: '确认人', dataIndex: 'confirmUserName', width: 120 },
      { title: '费用备注', dataIndex: 'remark', ellipsis: true, width: 140 },
      { title: '结算备注', dataIndex: 'settlementRemark', ellipsis: true, width: 140 },
    ],
    buttons: [
      {
        type: 'primary',
        label: '批量结算',
        permission: 'svms:asstes:operation:car-transfer.batchConfirm',
        method: () => {
          if (selectedRowKeys.value.length == 0) {
            Message.error('请选择需要批量结算的费用')
            return
          }
          // 批量结算时，传值选中项首项的supplierType、supplierName
          let changeId = selectedRowKeys.value[0]
          let tableData = tableCompulsory.dataList
          let changeObj = tableData.find((i) => i.id == changeId)
          checkBatchConfirm({ businesId: businesId.value, idList: selectedRowKeys.value, installmentList: installmentIds.value }).then(
            (res) => {
              if (res.code == 200 && res.result) {
                confirm_cost.value.open(selectedRowKeys.value, props.type)
              }
            }
          )
        },
      },
    ],
    operates: [
      {
        label: '结算',
        show: (record) => record.feeStatus == 0 || record.feeStatus == 3 || record.feeStatus == 5,
        permission: 'svms:asstes:operation:car-transfer.confirm_cost_modal',
        method: (record, column, rowIndex) => {
          handleConfirm(record, rowIndex)
        },
      },
      {
        label: '修改费用',
        show: (record) => record.feeStatus == 0 || record.feeStatus == 3 || record.feeStatus == 5,
        permission: 'svms:asstes:operation:car-transfer.edit_cost_modal',
        method: (record) => {
          handleEditFee(record)
        },
      },
    ],
    dataList: [],
  })

  // 字段处理
  const tabletolist = (list) => {
    list.forEach((el) => {
      el.mtype = 'MENU'
      el.level = 1
      el.checked = false
      // 跨门店借调费58 - 结构两层所以排除
      if (el.feeDetailList && el.feeDetailList.length && el.feeNameId !== 58) {
        el.children = el.feeDetailList
        el.children.forEach((pl) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          pl.feeNameId = el.feeNameId
          pl.feeName = pl.itemName
          pl.totalAmount = pl.amount
          pl.disabled = true
        })
      } else {
        return false
      }
    })
    return list
  }

  // 列表接口调用
  const loadData = () => {
    tableCompulsory.tableLoading = true
    getFeeInfoList({ ...queryParam }).then((res) => {
      if (res.code == 200) {
        tableCompulsory.tableLoading = false
        feeDetail.value = res.result
        tableCompulsory.dataList = tabletolist(res.result.carAssetFeeList) || []
        // 获取当前日期的23:59:59
        const currentDate = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
        selectedRowKeys.value = []
        tableCompulsory.dataList.map((it) => {
          const isFeeStatusValid = [0, 3, 5].includes(it.feeStatus)
          // 判断 dueDate 是否小于或等于当前日期
          const isDueDateValid = it.dueDate <= currentDate
          if (isFeeStatusValid && isDueDateValid) {
            selectedRowKeys.value.push(it.id)
          }
          // 根据判断条件设置 disabled
          it.disabled = !isFeeStatusValid
        })
        renderSelectId()
      }
    })
  }
  const selectedRowKeys = ref([])
  // 业务单ID
  const businesId = ref('')
  // 期数ID
  const installmentIds = ref([])
  const selectionChange = (e) => {
    selectedRowKeys.value = e
    renderSelectId()
  }
  const renderSelectId = () => {
    businesId.value = '' // 重新赋值空字符串
    installmentIds.value = [] // 清空 installmentIds 数组
    tableCompulsory.dataList.forEach((record) => {
      const index = selectedRowKeys.value.indexOf(record.id)
      if (index !== -1) {
        if (businesId.value === '') {
          businesId.value = record.businesId
        }
        installmentIds.value.push(record.payableNum)
      }
    })
  }
  const modifyCostRef = ref(null)
  const handleEditFee = (record) => {
    // 借调附加费 feeNameId 61
    //跨门店用车 - 借调费58
    if (record.feeNameId == 61 || record.feeNameId == 58) {
      modifyCostRef.value.open({
        id: record.id,
        feeNameId: record.feeNameId,
        feeCategory: record.feeCategory,
        installment: record.installment,
        businesId: feeDetail.value.businesId,
        businesCode: feeDetail.value.businesCode,
        carId: record.carId,
        feeNameId: record.feeNameId,
        title: `修改费用-${feeDetail.value.carLicenseNo}`,
      })
    } else {
      modifyCostRef.value.open({
        id: record.businesId,
        feeNameId: record.feeNameId,
        feeCategory: record.feeCategory,
        installment: record.installment,
        businesId: feeDetail.value.businesId,
        businesCode: feeDetail.value.businesCode,
        carId: record.carId,
        feeNameId: record.feeNameId,
        title: `修改费用-${feeDetail.value.carLicenseNo}`,
      })
    }
  }

  const confirm_cost = ref(null)
  const handleConfirm = (record, index) => {
    if (index != 0) {
      // 1:已付款 2:已收款
      if (tableCompulsory.dataList[index - 1].feeStatus == 1 || tableCompulsory.dataList[index - 1].feeStatus == 2) {
        confirm_cost.value.open(record.id, props.type)
      } else if (record.installment == 0) {
        confirm_cost.value.open(record.id, props.type)
      } else {
        Message.error('请按顺序结算')
      }
    } else {
      confirm_cost.value.open(record.id, props.type)
    }
  }

  const checkboxChange = (e, x) => {
    if (e) {
      selectedKeys.value.push(x)
    } else {
      selectedKeys.value.forEach((item, index) => {
        if (item == x) {
          selectedKeys.value.splice(index, 1)
        }
      })
    }
  }

  const handleConfirmToFetch = () => {
    loadData()
    selectedKeys.value = []
  }

  const refreshData = () => {
    loadData()
  }

  const setValue = computed(() => {
    let obj = {}
    selectedKeys.value.forEach((it) => {
      obj[it] = true
    })
    return obj
  })

  watch(
    () => [props.carId, props.code, props.type],
    (arr) => {
      queryParam.carId = arr[0]
      queryParam.businesCode = arr[1]
      queryParam.type = arr[2]
      loadData()
    }
  )
</script>

<style lang="less" scoped>
  .second-stage {
    width: 200px;
    margin-left: 260px;
  }
  .third-stage {
    width: 200px;
    margin-left: 30px;
  }
  .btn-box {
    width: 100%;
    display: inline-flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .blue-text {
    min-width: 50%;
    display: inline-flex;
    align-items: center;
    line-height: 32px;
    white-space: nowrap;
    cursor: pointer;
    user-select: none;
    height: 32px;
    font-size: 14px;
    border-radius: var(--border-radius-small);
    color: rgb(var(--primary-6));
    &:hover {
      font-weight: 600;
    }
  }
  .icon-custom {
    color: #0256ff;
    font-size: 20px;
  }
</style>
